﻿#region License
/*Copyright (c) 2010 Andrew Collard (andrewcollard@hotmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace TorchView.Store
{
  /// <summary>
  /// A loca file server used to back up files
  /// </summary>
  public class LocalFileStore : IFileStore
  {
    private const string DateTimeFormat = "yyyy/MM/dd HH:mm:ss";
    private readonly static Version FileVersion = new Version(1, 0);

    private IDictionary<string, FileBackupCollection> _FileStore;
    private string _RepositoryFile;
    private string _RepositoryLocation;

    private static LocalFileStore _Default;
    /// <summary>
    /// Get the default local file store for the current roaming user 
    /// </summary>
    public static LocalFileStore Default
    {
      get
      {
        if (_Default == null)
          _Default = new LocalFileStore(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\TorchView\LocalFileStore");
        return _Default;
      }
    }

    private LocalFileStore(string repositoryLocation)
    {
      _RepositoryLocation = repositoryLocation;
      _RepositoryFile = Path.Combine(repositoryLocation, "FileStore.xml");
      _FileStore = LoadFileStore();
    }

    private IDictionary<string, FileBackupCollection> LoadFileStore()
    {
      var dictionary = new Dictionary<string, FileBackupCollection>();
      if (File.Exists(_RepositoryFile))
      {
        try
        {
          XElement root = XElement.Load(_RepositoryFile);
          var gameFiles = root.Elements("Files").Select(g => LoadGameFiles(g));
          foreach (var gameFileSet in gameFiles)
            dictionary.Add(gameFileSet.Item1, gameFileSet.Item2);
        }
        catch (XmlException) { }
      }
      return dictionary;
    }

    private Tuple<string, FileBackupCollection> LoadGameFiles(XElement gameFileSet)
    {
      string name = gameFileSet.Attribute("Filename").Value;
      FileBackupCollection files = new FileBackupCollection(gameFileSet.Elements("File").Select(f =>
      {
        int version;
        var attribute = f.Attribute("Version");
        if (attribute == null || !int.TryParse(attribute.Value, out version))
          version = -1;

        DateTime date;
        attribute = f.Attribute("Date");
        if (attribute == null || !DateTime.TryParseExact(attribute.Value, DateTimeFormat, null, System.Globalization.DateTimeStyles.AssumeUniversal, out date))
          date = DateTime.MinValue;

        string filename = string.Empty;
        attribute = f.Attribute("StorageFilename");
        if (attribute != null)
          filename = attribute.Value;

        string comment = string.Empty;
        attribute = f.Attribute("Comment");
        if (attribute != null)
          comment = attribute.Value;

        return new FileBackup(name, version, filename, comment, date);
      }).ToList());
      return new Tuple<string, FileBackupCollection>(name, files);
    }

    private void SaveFileRepository()
    {
      XElement root = new XElement("TorchViewFileStore", new XAttribute("Version", FileVersion),
        _FileStore.Select(k => new XElement("Files", new XAttribute("Filename", k.Key),
          k.Value.Select(gf => new XElement("File", new XAttribute("Version", gf.Version), new XAttribute("Date", gf.StoreDate.ToString(DateTimeFormat)), new XAttribute("StorageFilename", gf.StorageFilename), new XAttribute("Comment", gf.Comments))))));
      root.Save(_RepositoryFile);
    }

    public ICollection<FileBackup> Get(string filename)
    {
      FileBackupCollection files;
      if (_FileStore.TryGetValue(filename, out files))
        return files.ToArray();
      return new FileBackup[0];
    }

    public FileBackup Store(string filename, string comment = "")
    {
      FileBackupCollection files;
      if (!_FileStore.TryGetValue(filename, out files))
      {
        files = new FileBackupCollection();
        _FileStore.Add(filename, files);
      }

      string backupFile = Guid.NewGuid().ToString() + ".bak";
      FileBackup fileBackup = new FileBackup(filename, files.LatestVersion + 1, backupFile, comment, DateTime.UtcNow);

      string targetFile = Path.Combine(_RepositoryLocation, fileBackup.StorageFilename);
      if (!Directory.Exists(_RepositoryLocation))
        Directory.CreateDirectory(_RepositoryLocation);
      File.Copy(filename, targetFile, true);
      files.Add(fileBackup);
      SaveFileRepository();
      return fileBackup;
    }

    public bool Delete(FileBackup fileBackup)
    {
      FileBackupCollection files;
      if (_FileStore.TryGetValue(fileBackup.Filename, out files))
      {
        if (files.Remove(fileBackup))
        {
          var backupFile = Path.Combine(_RepositoryLocation, fileBackup.StorageFilename);
          if (File.Exists(backupFile))
            File.Delete(backupFile);
          if (files.Count == 0)
            _FileStore.Remove(fileBackup.Filename);
          fileBackup.IsDeleted = true;
          SaveFileRepository();
          return true;
        }
      }
      return false;
    }

    public bool DeleteAll(string filename)
    {
      FileBackupCollection files;
      if (_FileStore.TryGetValue(filename, out files))
      {
        foreach (var file in files)
        {
          var backupFile = Path.Combine(_RepositoryLocation, file.StorageFilename);
          if (File.Exists(backupFile))
            File.Delete(backupFile);
          file.IsDeleted = true;
        }
        files.Clear();
        _FileStore.Remove(filename);
        SaveFileRepository();
        return true;
      }
      return false;
    }

    public bool Download(FileBackup fileBackup, string targetFile)
    {
      string sourceFile = Path.Combine(_RepositoryLocation, fileBackup.StorageFilename);
      File.Copy(sourceFile, targetFile, true);
      return true;
    }

    public void UpdateComments(FileBackup fileBackup, string comments)
    {
      if (fileBackup.IsDeleted)
        throw new ArgumentException("fileBackup cannot be deleted.");
      fileBackup.Comments = comments;
      SaveFileRepository();
    }

    #region IEnumerable<KeyValuePair<string,ICollection<GameFile>>> Members

    public IEnumerator<KeyValuePair<string, ICollection<FileBackup>>> GetEnumerator()
    {
      return _FileStore.Select(k => new KeyValuePair<string, ICollection<FileBackup>>(k.Key, k.Value.ToArray())).GetEnumerator();
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }

    #endregion
  }
}
